<template>
  <div class="tp h-full flex flex-col">
    <Header />

    <Content class="flex-1 overflow-auto">
      <div class="cp">
        <a-flex gap="middle">
          <div class="card" style="width: 32%">
            <a-input-search
              v-model:value="state.search.goodsName"
              placeholder="输入产品名称搜索"
              enter-button="查询"
              @search="onSearch"
            />

            <a-tabs v-model:activeKey="state.search.cateType" type="line">
              <a-tab-pane
                v-for="o in proCategoryType.filter((o) => o.value === 'P')"
                :key="o.value"
                :tab="o.label"
              >
                <a-flex gap="small" wrap="wrap" class="cate-sub">
                  <div
                    :class="['use', 'cell', state[o.value].cateCode === null ? 'active' : 'tacit']"
                    @click="state[o.value].cateCode = null"
                    >全部
                  </div>
                  <div
                    v-for="z in getCateSubList(o.value)"
                    :key="z.cateCode"
                    :class="[
                      'use',
                      'cell',
                      state[o.value].cateCode === z.cateCode ? 'active' : 'tacit',
                    ]"
                    @click="state[o.value].cateCode = z.cateCode"
                  >
                    {{ z.cateSubName }}
                  </div>

                  <div class="btn" v-if="getCateSubAll(o.value).length > state.foldMinCount">
                    <a-button
                      v-if="state[o.value].hasFold"
                      type="link"
                      size="small"
                      :icon="h(CaretDownOutlined)"
                      @click="state[o.value].hasFold = false"
                      >展开
                    </a-button>
                    <a-button
                      v-else
                      type="link"
                      size="small"
                      :icon="h(CaretUpOutlined)"
                      @click="state[o.value].hasFold = true"
                      >收起
                    </a-button>
                  </div>
                </a-flex>

                <div class="p-list">
                  <template v-if="state[o.value].pager.list?.length > 0">
                    <div
                      :class="[
                        'use p-card',
                        state[o.value].selectedSn.has(item.goodsSn) && 'active tri-active',
                      ]"
                      v-for="item in state[o.value].pager.list"
                      :key="item.goodsSn"
                      @click="onToggle(item, o.value)"
                    >
                      <a-flex gap="middle">
                        <a-image
                          :width="64"
                          :height="64"
                          :src="OSS_IMG_URL(item.goodsImage)"
                          :fallback="imgErrSrc"
                        />

                        <a-flex class="fill right" vertical :gap="2">
                          <div class="cn-medium title">{{ item.goodsName }}</div>
                          <div class="fill"></div>
                          <a-flex gap="small" justify="space-between">
                            <div class="price"
                              ><span class="d-regular value">{{ item.salePrice }}</span
                              ><span class="unit">元</span></div
                            >
                            <div class="desc" v-if="o.value === 'P'">
                              {{ item.specs }}
                            </div>
                          </a-flex>
                        </a-flex>

                        <div class="tri-symbol"></div>
                        <div v-if="state[o.value].selectedSn.has(item.goodsSn)" class="tri-checked">
                          <CheckOutlined />
                        </div>
                      </a-flex>
                    </div>

                    <div class="pagination">
                      <a-pagination
                        :default-page-size="state.pageSize"
                        size="small"
                        v-model:current="state[o.value].pager.currentPage"
                        :total="state[o.value].pager.totalCount"
                        show-size-changer
                        @showSizeChange="onShowSizeChange"
                      />
                    </div>
                  </template>
                  <a-empty v-else />
                </div>
              </a-tab-pane>
            </a-tabs>
          </div>
          <div class="fill card">
            <template v-for="o in proCategoryType.filter((o) => o.value === 'P')" :key="o.value">
              <div class="c-title">{{ o.label }}</div>
              <BasicTable
                @register="state[o.value].registerTable"
                :dataSource="state[o.value].selected"
                :scroll="{ y: 520 }"
              >
                <template #action="{ record }">
                  <TableAction
                    :divider="true"
                    :actions="[
                      {
                        popConfirm: {
                          title: `您确定要删除吗`,
                          confirm: () => onDelete(record, o.value),
                        },
                        color: 'success',
                        label: '删除',
                      },
                    ]"
                  />
                </template>
              </BasicTable>
            </template>
          </div>
        </a-flex>
      </div>
    </Content>

    <Footer class="">
      <a-flex align="center" justify="center" gap="middle" class="f-body">
        <a-button @click="router.back()"> 取消</a-button>
        <a-button type="primary" @click="onSave">保存</a-button>
      </a-flex>
    </Footer>
  </div>
</template>

<script setup>
  import { defineOptions, h, onActivated, reactive, watch } from 'vue';

  import Header from '@/widget/header.vue';
  import Content from '@/widget/content.vue';
  import { PAGE, POST } from '@/api/http';
  import { imgErrSrc, OSS_IMG_URL, proCategoryType } from '@/api/ds';
  import { CaretDownOutlined, CaretUpOutlined, CheckOutlined } from '@ant-design/icons-vue';
  import { BasicTable, TableAction, useTable } from '@/components/Table';
  import { InputNumber } from 'ant-design-vue';
  import Footer from '@/widget/footer.vue';
  import { useRouter } from 'vue-router';
  import { useMessage } from '@/hooks/web/useMessage';
  import { copy, isNil } from '@/api/util.js';

  const router = useRouter();
  const { createMessage } = useMessage();

  defineOptions({ name: 'StockInProduct' });

  const [registerTableP, tableP] = useTable({
    columns: [
      {
        title: '产品名称',
        dataIndex: 'goodsName',
        ellipsis: false,
      },
      {
        title: '规格',
        dataIndex: 'specs',
        ellipsis: false,
      },

      {
        title: '实收货数量',
        dataIndex: 'qty',
        ellipsis: false,
        customRender: ({ value, record }) => {
          return h('div', null, [
            h(InputNumber, {
              value,
              min: 0,
              max: 9999999,
              style: { width: '160px !important' },
              addonAfter: record.saleUnit || '',
              precision: 0,
              ['onUpdate:value']: (nVal) => {
                record.qty = nVal;
              },
            }),
          ]);
        },
      },
    ],
    pagination: false,
    useSearchForm: false,
    showTableSetting: false,
    bordered: true,
    showIndexColumn: false,
    rowKey: 'goodsSn',
    actionColumn: {
      title: '操作',
      align: 'center',
      width: 90,
      dataIndex: 'action',
      fixed: 'right',
      slots: { customRender: 'action' },
    },
  });

  const state = reactive({
    search: {
      selectStatus: 0,
      cateType: 'P',
      goodsName: null,
    },

    foldMinCount: 6,
    pageSize: 10,

    P: {
      registerTable: registerTableP,
      table: tableP,
      selectedSn: new Set(),
      selected: [],
      hasFold: true,
      cateCode: null,
      version: null,
      pager: {
        currentPage: 0,
      },
    },

    categoryList: [],
  });

  onActivated(() => {
    reset();
  });

  function reset() {
    const { P: target } = state;
    const selected = copy(window._inProduct_?.P ?? []);

    Object.assign(target, {
      selectedSn: new Set(selected.map((o) => o.goodsSn)),
      selected,
      hasFold: true,
      cateCode: null,
    });

    onSearch();
  }

  function getCateWatch(cateType) {
    const target = state[cateType];
    return `${target.cateCode || ''}-${target.pager.currentPage || 0}-${target.version || ''}`;
  }

  watch(
    () => getCateWatch('P'),
    () => doPager('P'),
  );

  function getCateSubAll(cateType) {
    return state.categoryList.filter((z) => z.cateType === cateType);
  }

  function getCateSubList(cateType) {
    const list = getCateSubAll(cateType);
    return state[cateType].hasFold ? list.slice(0, state.foldMinCount) : list;
  }

  function onSearch() {
    doCategoryList();
  }

  function doCategoryList() {
    const { cateType, P } = state;

    POST('/product/libCategoryStoreListAll', { status: 1, cateType }).then((list) => {
      state.categoryList = list || [];

      [P].forEach((target) => {
        target.cateCode = null;
        target.pager.currentPage = 1;
        target.version = Math.random();
      });
    });
  }

  function doPager(cateType) {
    const { goodsName } = state.search;
    const { [cateType]: target, pageSize } = state,
      { cateCode, pager } = target,
      { currentPage } = pager;

    const url = '/product/productStoreList';
    PAGE(url)({ goodsName, thirdCateCode:cateCode, currentPage, pageSize }).then((result) => {
      target.pager = result ?? {};
    });
  }

  function onShowSizeChange(current, size) {
    state.pageSize = size
    doPager(state.search.cateType)
  }

  function onToggle(record, cateType) {
    const { selectedSn, selected } = state[cateType];
    const { goodsSn } = record;

    if (selectedSn.has(goodsSn)) {
      onDelete(record, cateType);
    } else {
      selectedSn.add(goodsSn);
      selected.push({ ...record, qty: null });
    }
  }

  function onDelete({ goodsSn }, cateType) {
    const { selectedSn, selected } = state[cateType];
    const index = selected.findIndex((o) => o.goodsSn === goodsSn);

    if (index > -1) {
      selected.splice(index, 1);
    }

    selectedSn.delete(goodsSn);
  }

  async function onSave() {
    const { P } = state;
    const [productList] = [P.selected];

    for (const { goodsName, qty } of productList) {
      if (isNil(qty) || qty < 1) {
        createMessage.error(`请输入“${goodsName}”实收货数量`);
        return;
      }
    }

    window._inProduct_ = copy({ P: productList });
    router.back();
  }
</script>
<style lang="less" scoped>
  .card {
    height: 100%;
    padding: 16px;

    .c-title {
      padding: 32px 0 6px 8px;
      color: #091f3d;
      font-size: 15px;
      font-weight: 600;
    }

    .c-title:first-child {
      padding-top: 8px;
    }
  }

  .cate-sub {
    position: relative;
    cursor: pointer;

    .cell {
      padding: 3px 12px;
      border-radius: 24px;
      font-size: 14px;
      font-weight: 400;
    }

    .tacit {
      border: 1px solid #e0e5ec;
      color: #091f3d;
    }

    .active {
      border: 1px solid @primary-color;
      background-color: @primary-color;
      color: #fff;
    }

    .btn {
      position: absolute;
      z-index: 2;
      right: 0;
      bottom: 0;
    }
  }

  .p-list {
    margin: 24px 0 0;

    .p-card {
      position: relative;
      margin: 12px 0;
      overflow: clip;
      border: 1px solid #e0e5ec;
      border-radius: 4px;

      .right {
        padding: 8px 32px 8px 0;

        .title {
          color: #091f3d;
          font-size: 14px;
        }

        .price {
          color: @primary-color;

          .value {
            font-size: 14px;
            letter-spacing: 1px;
          }

          .unit {
            padding-left: 2px;
            font-size: 10px;
          }
        }

        .desc {
          color: #acb4bf;
          font-size: 12px;
        }
      }
    }

    .pagination {
      text-align: right;
    }

    .active {
      border: 1px solid @primary-color;
    }
  }
</style>
